package dev.blogmoon.cn.admin.controller;

import com.google.common.collect.Lists;
import dev.blogmoon.cn.common.entity.Result;
import dev.blogmoon.cn.system.module.FileInfoDTO;
import dev.blogmoon.cn.system.module.QueryFileReq;
import dev.blogmoon.cn.system.repository.FileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequestMapping("/api/v1/admin/file")
@RestController
public class FileController {

    @Autowired
    private FileRepository fileRepository;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, @RequestParam("url") String url) throws IOException {
        String path = fileRepository.upload(file, url);
        return Result.success(path);
    }

    @PostMapping("/batch/upload")
    public Result upload(@RequestParam("files") MultipartFile[] files, @RequestParam("url") String url) throws IOException {
        List<String> pathList = fileRepository.upload(files, url);
        return Result.success(pathList);
    }


    @PostMapping("/list-dir")
    public Result getFileList(@RequestBody QueryFileReq req) {
        List<FileInfoDTO> fileList = Lists.newArrayList();
        if (Objects.equals(0, req.getFileType())) {
            fileList = fileRepository.getFileList(req.getPrefix(), "/");
            return Result.success(fileList);
        }
        fileList = fileRepository.getFileList(req.getPrefix(), req.getDelimiter());
        fileList = fileList.stream().filter(item -> {
            if (Objects.isNull(req.getPrefix())) {
                return true;
            }
            return Objects.equals(item.getFileType(), req.getFileType());
        }).collect(Collectors.toList());
        return Result.success(fileList);
    }


}
